﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using ZP.Common;
using ZP.IBLL;
using ZP.IDAL;
using ZP.Model;

namespace ZP.BLL
{
    public class ht_type1_fileService : BaseService<ht_type1_file, int>, Iht_type1_fileService
    {
        //public ht_type1_fileService(Iht_type1_fileDAL _ht_type1_fileDAL, Iht_type1_bakDAL _ht_type1_bakDAL)
        //{
        //    this._repository = _ht_type1_fileDAL;
        //    this._ht_type1_bakDAL = _ht_type1_bakDAL;
        //}

        public bool DeleteEPFile(int ep_id, Guid file_id, out string fl_phy_add)
        {
            bool result = false;
            fl_phy_add = "";
            var updateQuery = _repository.GetModels(p => p.ep_id == ep_id && p.id == file_id);
            //1.将需要删除的文件备份到ht_type1_bak
            var deleteEntity = updateQuery.FirstOrDefault();
            if (deleteEntity == null)
            {
                return false;
            }
            fl_phy_add = deleteEntity.fl_phy_add;

            string filepath = HttpRuntime.AppDomainAppPath + ZPCommon.Upload_Save_DIR + fl_phy_add;     //原文件地址
            string filepath_bak = HttpRuntime.AppDomainAppPath + ZPCommon.Upload_BAK_DIR + fl_phy_add;  //备份目录
            string filepath_bakdir = filepath_bak.Substring(0, filepath_bak.LastIndexOf('/'));  //过滤掉文件名称只保留目录
            //物理文件存在
            if (!string.IsNullOrWhiteSpace(fl_phy_add) && System.IO.File.Exists(filepath))
            {
                //将文件复制到备份目录
                if (!Directory.Exists(filepath_bakdir))
                {
                    Directory.CreateDirectory(filepath_bakdir);
                }
                File.Copy(filepath, filepath_bak, true);

                var type1Bak = new ht_type1_bak { id = Guid.NewGuid(), ep_id = deleteEntity.ep_id, ht_id = deleteEntity.ht_id, ft_id = deleteEntity.ft_id, fl_name = deleteEntity.fl_name, fl_phy_add = deleteEntity.fl_phy_add, fl_cover_time = DateTime.Now };
                _ht_type1_bakDAL.Add(type1Bak);
            }

            //2.将源附件删除
            int deleteCount = updateQuery.DeleteFromQuery();
            result = deleteCount > 0;
            if (result)
            {
                //删除物理文件
                if (!string.IsNullOrWhiteSpace(fl_phy_add) && System.IO.File.Exists(filepath))
                {
                    System.IO.File.Delete(filepath);
                }
            }
            return result;
        }

        public Guid SaveEPFile(int ep_id, int ht_id, int ft_id, string fl_name, string fl_phy_add)
        {
            Guid id = Guid.NewGuid();
            ht_type1_file entity = new ht_type1_file { id = id, ep_id = ep_id, ht_id = ht_id, ft_id = ft_id, fl_name = fl_name, fl_phy_add = fl_phy_add, fl_updatetime = DateTime.Now };
            _repository.Add(entity);
            return id;
        }
    }
}
